package tako.wisers.com.android.apis.http;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import tako.wisers.com.android.apis.activity.LoadingActivity;
import tako.wisers.com.android.apis.activity.Tako;
import tako.wisers.com.android.apis.database.SQListManager;
import tako.wisers.com.android.apis.parser.ConfXMLParser;
import tako.wisers.com.android.apis.parser.StationXMLParser;
import tako.wisers.com.android.apis.util.Global;

public class ConfLoadService {
	private boolean mIsLoading;
	private Activity mActivity;
	private String mAppName;
	private String mTel;
	
	public final static String HEADER_TEL_KEY = "tel";
	public final static String HEADER_APP_KEY = "app";
	public final static String HEADER_VERSION_KEY = "version";
	
	public ConfLoadService(String appName, String tel, Activity activity){
		mActivity = activity;
		mAppName = appName;
		mTel = tel;
		mIsLoading = false;
	}
	
	class ConfLoadThread extends Thread{
		@Override
		public void run() {
			load();
			mIsLoading = false;
		}
		private void load(){
			StationXMLParser.getInstance();
			SQListManager.build(mActivity.getApplicationContext());
			SQListManager sqlm = SQListManager.getInstance();
			sqlm.createTable(SQListManager.TABLE_INDATABASE);
			sqlm.createTable(SQListManager.TABLE_INMEMORY);
			String url = String.format(Global.FILE_CONFIG_URL, mTel, mAppName);
			HttpGeter geter = new HttpGeter(url);
			String version = geter.getHeader(HEADER_VERSION_KEY);
			System.gc();
//			if(version == null) {
//				android.os.Process.killProcess(android.os.Process.myPid());
//				return ;
//			}
			try {
				File confFile = new File(Global.DOWNLOAD_CONFIG_PATH);
				makeDir(confFile.getParentFile());
				String encode = "utf-8";
				if(confFile.exists()){
					FileInputStream fis = new FileInputStream(confFile);
					String xml = IOUtils.toString(fis, encode);
					IOUtils.closeQuietly(fis);
					String localVersion = StringUtils.substringBetween(xml, "<version>", "</version>");
					if(version == null || (localVersion != null && localVersion.equals(version))){
						ConfXMLParser.create(true, new ByteArrayInputStream(xml.getBytes(encode)));
						toTako();
						return;
					}
				}
				InputStream isIntenet = geter.getInputStream();
				String confStr = IOUtils.toString(isIntenet, encode);
				IOUtils.closeQuietly(isIntenet);
				ByteArrayInputStream baos = new ByteArrayInputStream(confStr.getBytes(encode));
				ConfXMLParser.create(false, baos);
				toTako();
				FileOutputStream fos = new FileOutputStream(confFile);
				fos.write(confStr.getBytes(encode));
				fos.flush();
				fos.close();
				System.gc();
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		private void toTako() {
			Context cxt = mActivity.getApplicationContext();
			Intent intent = new Intent();
			intent.setClass(cxt, Tako.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			cxt.startActivity(intent);
			mActivity.finish();
		}
	}
	
	public synchronized static boolean makeDir(File file){
		if(file.exists()){
			return true;
		}else if(makeDir(file.getParentFile())){
			return file.mkdir();
		}else{
			return false;
		}
	}
	
//	private static File findExistsDir(File file) {
//		
//	}
	
	public void loadConf(){
		mIsLoading = true;
		ConfLoadThread thread = new ConfLoadThread();
		thread.start();
	}
	
}
